package com.ymk.cmd;

import com.ymk.base.cmd.ACmd;
import com.ymk.base.cmd.CmdSign;
import com.ymk.base.exception.MallException;
import com.ymk.base.utlis.DateUtil;
import com.ymk.base.utlis.ParamsBuilder;
import com.ymk.bo.user.UserInfoBO;
import com.ymk.bo.user.UserRefreshBO;
import com.ymk.bo.work.WorkShareLogBO;
import com.ymk.core.code.cmd.OrdersCmdCode;
import com.ymk.core.code.cmd.UserCmdCode;
import com.ymk.core.code.cmd.WorkShareLogCmdCode;
import com.ymk.core.code.req.ReqCode;
import com.ymk.core.constants.MemberConstants;
import com.ymk.core.constants.SysConstants;
import com.ymk.core.constants.WxConstants;
import com.ymk.entity.WorkShareLog;
import com.ymk.service.IUserInfoService;

import com.ymk.service.IUserRefreshService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Service
public class UserGetCmd extends ACmd {

    @Override
    public CmdSign executeMop(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        String openId = request.getHeader(WxConstants.X_WX_OPENID);

        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("wxOpenId", openId)
                .setReturnStruct(sign.getReturnStruct());
        UserInfoBO respData = this.userService.get(paramsBuilder.build());

        if (!Objects.isNull(respData)) {
            respSign.setSource(super.getSource(respData));
        } else {
            respData = new UserInfoBO();
            respData.setWxOpenId(openId);
            respData.setUserId(DateUtil.getDateUUid());
            respData.setName(MemberConstants.MEMBER_DEFAULT_NAME);
            this.setCreatedData(respSign, respData);
            this.userService.post(respData);
            respSign.setSource(super.getSource(respData));
        }

        return respSign;
    }

    @Override
    public CmdSign executeSop(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        UserInfoBO reqData = super.getData(sign, UserInfoBO.class);
        String openId = request.getHeader(WxConstants.X_WX_OPENID);
        UserInfoBO oldUser = null;
        boolean flag = false;

        if (MemberConstants.USER_REFRESH.equals(respSign.getReqCode())) {
            flag = true;
            ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                    .addParam("userId", reqData.getOldUserId())
                    .setReturnStruct(sign.getReturnStruct());
             oldUser = this.userService.get(paramsBuilder.build());
            if (Objects.isNull(oldUser)) {
                throw new MallException("用户" + reqData.getOldUserId() + "不存在。");
            }

        }

        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("wxOpenId", openId)
                .setReturnStruct(sign.getReturnStruct());
        UserInfoBO respData = this.userService.get(paramsBuilder.build());
        if (!Objects.isNull(respData)) {
            respSign.setSource(super.getSource(respData));
            if (flag) {
                //岗位分享记录统计
                getNewWork(request,sign,respData,oldUser);
            }

        } else {
            respData = new UserInfoBO();
            respData.setWxOpenId(openId);
            respData.setUserId(DateUtil.getDateUUid());
            respData.setName(MemberConstants.MEMBER_DEFAULT_NAME);
            this.setCreatedData(respSign, respData);
            this.userService.post(respData);
            respSign.setSource(super.getSource(respData));

            if (flag) {
                // 用户拉新
                getNewUser(sign, respData, oldUser);
                //岗位分享记录统计
                getNewWork(request,sign,respData,oldUser);
            }

        }


        return respSign;
    }

    @Override
    public CmdSign executeServer(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        UserInfoBO reqData = super.getData(sign, UserInfoBO.class);

        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("userId", reqData.getUserId())
                .setReturnStruct(sign.getReturnStruct());
        UserInfoBO respData = this.userService.get(paramsBuilder.build());


        respSign.setSource(super.getSource(respData));

        return respSign;
    }

    private void getNewUser(CmdSign sign, UserInfoBO newUser, UserInfoBO oldUser) throws Exception {

        //用户拉新记录统计
        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("oldUserId", oldUser.getUserId())
                .addParam("newUserId", newUser.getUserId())
                .setReturnStruct(sign.getReturnStruct());
        UserRefreshBO userRefreshBO = userRefreshService.get(paramsBuilder.build());
        if (Objects.isNull(userRefreshBO)) {
            userRefreshBO = new UserRefreshBO();
            userRefreshBO.setNewUserId(newUser.getUserId());
            userRefreshBO.setOldUserId(oldUser.getUserId());
            this.setCreatedData(sign, userRefreshBO);
            userRefreshService.post(userRefreshBO);
        }


    }

    private void getNewWork(HttpServletRequest request, CmdSign sign, UserInfoBO newUser,UserInfoBO oldUser) throws Exception {
        UserInfoBO reqData = super.getData(sign, UserInfoBO.class);

        // 岗位分享记录统计
        WorkShareLogBO workShareLogBO = new WorkShareLogBO();
        workShareLogBO.setWorkId(reqData.getWorkId());
        workShareLogBO.setSharerUserId(oldUser.getUserId());
        workShareLogBO.setReceiverUserId(newUser.getUserId());
        CmdSign ordersPatchCmd = CmdSign.Builder.newBuild(sign)
                .setSource(workShareLogBO)
                .setCmdCode(WorkShareLogCmdCode.WORK_SHARE_LOG_POST)
                .setScope(SysConstants.CMD_SERVER_SCOPE)
                .build();
        this.scheduler.schedule(request, ordersPatchCmd);


    }

    @Override
    public String getCmdCode() {
        return UserCmdCode.USER_GET;
    }

    @Override
    public boolean anon(CmdSign sign) {
        return true;
    }

    @Override
    public CmdSign verify(HttpServletRequest request, CmdSign sign) throws Exception {

        String openId = request.getHeader(WxConstants.X_WX_OPENID);
        if (StringUtils.isBlank(openId)) {
            throw new MallException("请求异常,header未发现openID");
        }

        return null;
    }

    @Autowired
    private IUserInfoService userService;

    @Autowired
    private IUserRefreshService userRefreshService;
}